package uk.co.q3c.deplan.client.domain.resource;

import java.util.Date;
import java.util.Stack;
import java.util.logging.Logger;

import uk.co.q3c.deplan.client.dao.DatabaseCommitListener;
import uk.co.q3c.deplan.client.dao.ResourceService;
import uk.co.q3c.deplan.client.domain.PropertyChangeEvent;
import uk.co.q3c.deplan.client.domain.PropertyChangeListener;

public class ResourceManager {
	private static Logger logger = Logger.getLogger(ResourceManager.class.getName());
	ResourceService resourceDao;

	private final Stack<PropertyChangeEvent> changeEvents = new Stack<PropertyChangeEvent>();
	boolean loaded = false;
	ResourcePool resourcePool;
	Date levelDate;
	ResourcePropertyListener propertyChangeListener;

	class CommitListener implements DatabaseCommitListener {

		@Override
		public void afterCommit() {
			changeEvents.clear();
			logger.info("Event list cleared");
		}

		@Override
		public void beforeCommit() {
			// do nothing
		}

		@Override
		public void afterRollback() {
			changeEvents.clear();
			logger.info("Event list cleared");

		}

		@Override
		public void beforeRollback() {
			// do nothing
		}
	}

	class ResourcePropertyListener implements PropertyChangeListener {

		@Override
		public void propertyChange(PropertyChangeEvent evt) {
			Resource r = (Resource) evt.getSource();
			logger.info("Observing property change in resource" + r);
			changeEvents.push(evt);
			resourceDao.save(r);
		}

	}

	public ResourceManager() {

		if (!loaded) {
			load();
		}

		// add property listener to all

		// Model.getDbc().addListener(new CommitListener());
	}

	private void load() {
		resourcePool = resourceDao.findResourcePools()
				.get(0);
		resourcePool.addPropertyChangeListener(propertyChangeListener);
		loaded = true;
	}

	/**
	 * This is a SYSTEM RESOURCE not a dePlan Resource
	 */
	// @Override
	// public void resourceChanged(IResourceChangeEvent event) {
	// // TODO Auto-generated method stub
	//
	// }

	public void rename(Resource resource, String newName) {
		resource.setName(newName);

	}

	public ResourcePool getResourcePool() {
		return resourcePool;
	}

}
